/**
 * 
 */
package com.geezdata.cps.sdk3rd.wechat.method;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.geezdata.cps.base.enums.ErrorCode;
import com.geezdata.cps.base.exceptions.MyException;
import com.geezdata.cps.base.utils.HttpClientUtil;
import com.geezdata.cps.sdk3rd.wechat.response.WechatResult;

/**
 * @author sszheng
 * @date 创建时间：2018年4月10日 下午5:26:01
 *
 */
public abstract class BaseWechat {
	private static Logger logger = LoggerFactory.getLogger(BaseWechat.class);
	
	protected boolean isExpired(JSONObject jsonObject) {
		Integer errcode = jsonObject.getIntValue("errcode");
		if(errcode != null && (errcode == 40001 || errcode == 42001)) {
			return true;
		}
		return false;
	}
	
	public <V extends WechatResult> V doPost(String url, Map<String, Object> params, Class<V> targetClazz) {
		String merchantName = getMethodName();
		String rspStr = null;
		try {
        	rspStr = HttpClientUtil.post(url, params);
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	return null;
        }
		
		if (rspStr == null) {
			logger.info( merchantName + " url {}", url);
        	logger.info( merchantName + " params {}", JSON.toJSONString(params));
        	throw new MyException(ErrorCode.INTERNAL_SERVER_ERROR.getCode(), merchantName + " failed "); 
		}
		
		JSONObject jsonObject = JSONObject.parseObject(rspStr);
		if(isExpired(jsonObject)) {
			V result = null;
			try {
				result = targetClazz.newInstance();
			} catch (InstantiationException | IllegalAccessException e) {
				logger.error(e.getMessage(), e);
			}
			result.setExpired(true);
			return result;
		}
		
		V result = JSONObject.toJavaObject(jsonObject, targetClazz);
		return result;	
	};
	
	private String getMethodName() {  
        StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();  
        StackTraceElement e = stacktrace[3];  
        String methodName = e.getMethodName();  
        return methodName;  
    }  
}
